# admin/admin_member.py

from flask import Blueprint, render_template, redirect, url_for, flash, request, make_response, jsonify
from flask_login import login_required, current_user
import io
import csv
from datetime import datetime

from inc.models import AdminMember, AdminDepartment, AdminUser, OperationLog, db,  User

from admin.admin.admin_class import MemberForm




admin_member_bp = Blueprint('admin_member', __name__)






@admin_member_bp.route('/api/departments')
@login_required
def api_departments():
    company_name = request.args.get('company_name')
    if not company_name:
        return jsonify([])

    departments = AdminDepartment.query.join(
        AdminMember, AdminMember.department_id == AdminDepartment.id
    ).join(
        User, AdminMember.wecom_userid == User.wecom_userid
    ).filter(
        User.tags.like(f'%{company_name}%')
    ).distinct().all()

    return jsonify([{
        'id': dept.id,
        'name': dept.name
    } for dept in departments])

# 允许的文件扩展名
ALLOWED_EXTENSIONS = {'csv', 'xlsx', 'xls'}

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@admin_member_bp.route('/members')
@login_required
def member_management():
    # 获取分页参数
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 20, type=int)

    # 构建优化查询
    query = (
        db.session.query(
            AdminMember.id,
            AdminMember.name,
            AdminMember.mobile,
            AdminMember.email,
            AdminMember.department_id,
            AdminMember.position,
            AdminMember.status,
            AdminMember.wecom_userid,
            AdminDepartment.name.label('department_name'),
            User.tags.label('company_name'),
        )
        .outerjoin(User, AdminMember.wecom_userid == User.wecom_userid)
        .outerjoin(AdminDepartment, AdminMember.department_id == AdminDepartment.id)
    )

    # 处理搜索条件
    name = request.args.get('name')
    if name:
        query = query.filter(AdminMember.name.like(f'%{name}%'))

    company_name = request.args.get('company_name')
    if company_name:
        query = query.filter(User.tags.like(f'%{company_name}%'))

    department_id = request.args.get('department_id')
    if department_id and department_id != '0':
        query = query.filter(AdminMember.department_id == department_id)

    status = request.args.get('status')
    if status in ('0', '1'):
        query = query.filter(AdminMember.status == int(status))

    # 执行分页查询
    query = query.order_by(AdminMember.id.desc())
    members = query.paginate(page=page, per_page=per_page, error_out=False)

    # 获取所有公司（从wx_user.tags）
    companies = db.session.query(User.tags.distinct().label('company')).filter(User.tags != None).all()
    companies = [c.company for c in companies if c.company]  # 转换为列表

    # 获取所有部门
    departments = AdminDepartment.query.all()

    # 将搜索参数转换为字典
    search_params = request.args.to_dict()
    if 'page' in search_params:
        del search_params['page']

    return render_template(
        'admin/admin/admin_member.html',
        members=members,
        departments=departments,
        companies=companies,
        search_params=search_params
    )



@admin_member_bp.route('/members/add', methods=['GET', 'POST'])
@login_required

def add_member():
    form = MemberForm()
    form.department.choices = [(0, '-- 选择部门 --')] + [(d.id, d.name) for d in AdminDepartment.query.all()]
    if form.validate_on_submit():
        try:
            member = AdminMember(
                name=form.name.data,
                mobile=form.mobile.data,
                email=form.email.data,
                department_id=form.department.data if form.department.data != 0 else None,
                position=form.position.data,
                status=form.status.data,
                wecom_userid=form.wecom_userid.data if form.wecom_userid.data else None
            )
            db.session.add(member)
            log = OperationLog(
                admin_id=current_user.id,
                action="添加员工",
                resource="AdminMember",
                details=f"添加员工: {form.name.data}",
                success=True,
                ip_address=request.remote_addr
            )
            db.session.add(log)
            db.session.commit()
            flash('员工已添加', 'success')
            return redirect(url_for('admin.admin_member.member_management'))
        except Exception as e:
            db.session.rollback()
            flash(f'添加员工时出错: {str(e)}', 'danger')
    return render_template('admin/admin/admin_memberadd.html', form=form, title='添加员工')



@admin_member_bp.route('/members/edit/<int:id>', methods=['GET', 'POST'])
@login_required

def edit_member(id):
    member = AdminMember.query.get_or_404(id)
    form = MemberForm(obj=member)
    form.department.choices = [(0, '-- 选择部门 --')] + [(d.id, d.name) for d in AdminDepartment.query.all()]
    if member.department_id:
        form.department.data = member.department_id




    if form.validate_on_submit():
        try:
            member.name = form.name.data
            member.mobile = form.mobile.data
            member.email = form.email.data
            member.department_id = form.department.data if form.department.data != 0 else None
            member.position = form.position.data
            member.status = form.status.data
            member.wecom_userid = form.wecom_userid.data if form.wecom_userid.data else None
            log = OperationLog(
                admin_id=current_user.id,
                action="编辑员工",
                resource="AdminMember",
                details=f"编辑员工: {form.name.data}",
                success=True,
                ip_address=request.remote_addr
            )
            db.session.add(log)
            db.session.commit()
            flash('员工已更新', 'success')
            return redirect(url_for('admin.admin_member.member_management'))
        except Exception as e:
            db.session.rollback()
            flash(f'更新员工时出错: {str(e)}', 'danger')
    return render_template('admin/admin/admin_memberadd.html', form=form, title='编辑员工', member=member)

@admin_member_bp.route('/members/import', methods=['GET', 'POST'])
@login_required

def import_members():
    """批量导入成员"""
    if request.method == 'POST':
        if 'file' not in request.files:
            flash('未选择文件', 'danger')
            return redirect(request.url)

        file = request.files['file']
        if file.filename == '':
            flash('未选择文件', 'danger')
            return redirect(request.url)

        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            try:
                # 根据文件类型处理
                if filename.endswith('.csv'):
                    # 处理CSV文件
                    stream = io.StringIO(file.stream.read().decode("UTF8"), newline=None)
                    csv_reader = csv.DictReader(stream)

                    imported = 0
                    for row in csv_reader:
                        # 验证必填字段
                        if not all(k in row for k in ['name', 'mobile', 'email']):
                            continue

                        member = AdminMember(
                            name=row['name'],
                            mobile=row['mobile'],
                            email=row['email'],
                            department_id=int(row['department_id']) if row.get('department_id') else None,
                            position=row.get('position', ''),
                            status=int(row.get('status', 1)),
                            create_time=datetime.now()
                        )
                        db.session.add(member)
                        imported += 1

                    if imported > 0:
                        db.session.commit()
                        flash(f'成功导入 {imported} 条成员记录', 'success')
                    else:
                        flash('未导入任何记录，请检查文件格式', 'warning')

                # TODO: 添加Excel文件处理

                return redirect(url_for('admin_member.member_management'))

            except Exception as e:
                db.session.rollback()
                flash(f'导入失败: {str(e)}', 'danger')
                return redirect(request.url)

    return render_template('admin/admin/admin_member_import.html')

@admin_member_bp.route('/members/export')
@login_required

def export_members():
    """导出成员为CSV"""
    try:
        members = AdminMember.query.all()

        output = io.StringIO()
        writer = csv.writer(output)

        # 写入表头
        writer.writerow([
            '姓名', '手机号', '邮箱',
            '部门ID', '职位', '状态'
        ])

        # 写入数据
        for member in members:
            writer.writerow([
                member.name,
                member.mobile,
                member.email,
                member.department_id or '',
                member.position or '',
                member.status
            ])

        # 准备响应
        output.seek(0)
        response = make_response(output.getvalue())
        response.headers['Content-Disposition'] = 'attachment; filename=members_export.csv'
        response.headers['Content-type'] = 'text/csv'
        return response

    except Exception as e:
        flash(f'导出失败: {str(e)}', 'danger')
        return redirect(url_for('admin.admin_member.member_management'))

@admin_member_bp.route('/members/template')
@login_required

def download_template():
    """下载导入模板"""
    try:
        output = io.StringIO()
        writer = csv.writer(output)

        # 模板表头
        writer.writerow([
            'name', 'mobile', 'email',
            'department_id', 'position', 'status'
        ])
        writer.writerow([
            '姓名(必填)', '手机号(必填)', '邮箱(必填)',
            '部门ID(可选)', '职位(可选)', '状态(1-启用, 0-禁用, 默认1)'
        ])

        output.seek(0)
        response = make_response(output.getvalue())
        response.headers['Content-Disposition'] = 'attachment; filename=member_import_template.csv'
        response.headers['Content-type'] = 'text/csv'
        return response

    except Exception as e:
        flash(f'模板下载失败: {str(e)}', 'danger')
        return redirect(url_for('admin.admin_member.member_management'))

@admin_member_bp.route('/members/delete/<int:id>')
@login_required

def delete_member(id):
    member = AdminMember.query.get_or_404(id)
    if AdminUser.query.filter_by(member_id=id).count() > 0:
        flash('无法删除有关联用户的员工', 'danger')
        return redirect(url_for('admin.admin_member.member_management'))
    try:
        db.session.delete(member)
        log = OperationLog(
            admin_id=current_user.id,
            action="删除员工",
            resource="AdminMember",
            details=f"删除员工: {member.name}",
            success=True,
            ip_address=request.remote_addr
        )
        db.session.add(log)
        db.session.commit()
        flash('员工已删除', 'success')
    except Exception as e:
        db.session.rollback()
        flash(f'删除员工时出错: {str(e)}', 'danger')
    return redirect(url_for('admin.admin_member.member_management'))


